﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using Sausage.Web.DataModel;

namespace Sausage.Web.Domain
{
    public class UserPrincipal : GenericPrincipal
    {
        #region Properties
        private Guid _userID;
        public Guid UserID
        {
            get { return _userID; }
        }

        private List<Role> _roleList;
        public List<Role> RoleList
        {
            get
            {
                if (_roleList == null)
                    _roleList = RoleHelper.GetRoleListByUser(User);
                return _roleList;
            }
        }

        private List<Guid> _roleIDList;
        public List<Guid> RoleIDList
        {
            get
            {
                if (_roleIDList == null)
                    _roleIDList = RoleList.Select(item => item.RoleID).ToList();
                return _roleIDList;
            }
        }

        private User _user;
        public User User
        {
            get
            {
                if (_user == null)
                    _user = UserHelper.GetUserByID(_userID);
                return _user;
            }
        }

        private List<MenuInfo> _meanList;
        public List<MenuInfo> MeanList
        {
            get
            {
                if (_meanList == null)
                {
                    _meanList = MenuHelper.GetMenuListByRole(this.RoleList);
                }
                return _meanList;
            }
        }

        private Organization _organization;
        public Organization Organization
        {
            get
            {
                if (_organization == null)
                    _organization = OrganizationHelper.GetOrganizationByID(User.OrganizationID);
                return _organization;
            }
        }

        #endregion

        public UserPrincipal(IIdentity identity, string[] roles)
            : base(identity, roles)
        {
            _userID = Guid.Parse(this.Identity.Name);
        }

        public override bool IsInRole(string role)
        {
            return null !=
                   RoleList.FirstOrDefault(
                       item => string.Compare(item.RoleName, role, StringComparison.InvariantCultureIgnoreCase) == 0);
        }

        public bool IsDistrictOrganization
        {
            get { return OrganizationHelper.IsDistrictOrganization(this.User.OrganizationID); }
        }
    }
}
